/*
 * Galaxium Messenger
 * Copyright (C) 2003-2007 Philippe Durand <draekz@gmail.com>
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * Copyright (C) 2007-2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;
using System.Xml;

using Anculus.Core;
using Galaxium.Core;

namespace Galaxium.Protocol.Msn
{
	public class MsnWink : MsnObject
	{
		XmlDocument _contentDesc = null;
		string _thumbnail = string.Empty;
		string _animation = string.Empty;
		int _width = 0;
		int _height = 0;
		
		public byte[] Stamp
		{
			get { return Convert.FromBase64String (Xml.GetAttribute ("stamp")); }
			set { Xml.SetAttribute ("stamp", Convert.ToBase64String (value)); }
		}
		
		public string Animation
		{
			get { return _animation; }
		}
		
		public string Thumbnail
		{
			get { return _thumbnail; }
		}
		
		public int Width
		{
			get { return _width; }
		}
		
		public int Height
		{
			get { return _height; }
		}
		
		internal MsnWink (MsnSession session)
			: base (session)
		{
			Type = MsnObjectType.Wink;
		}
		
		public MsnWink (MsnSession session, string context)
			: base (session, context)
		{
			Type = MsnObjectType.Wink;
		}
		
		public static MsnWink FromPackage (MsnSession session, string filename)
		{
			string dir = CabExtract.Instance.ExtractToDirectory (filename);
			
			if (string.IsNullOrEmpty (dir))
			{
				Log.Error ("Unable to extract package {0}", filename);
				return null;
			}
			
			string contentFile = Path.Combine (dir, "content.xml");
			
			if (!File.Exists (contentFile))
			{
				Log.Error ("No content file");
				return null;
			}
			
			XmlDocument xml = new XmlDocument ();
			xml.Load (contentFile);
			
			if (!xml.DocumentElement.Name.Equals ("package", StringComparison.InvariantCultureIgnoreCase))
			{
				Log.Error ("Invalid package");
				return null;
			}
			
			foreach (XmlElement elem in xml.DocumentElement)
			{
				if (elem.Name != "item")
					continue;
				
				string file = Path.Combine (dir, elem.GetAttribute ("file"));
				string stamp = elem.GetAttribute ("stamp");
				
				file = FindCorrectCase (file);
				
				if (string.IsNullOrEmpty (file) || (!File.Exists (file)))
				{
					Log.Error ("Unable to find data file");
					return null;
				}
				
				MsnWink wink = new MsnWink (session);
				wink.Stamp = Convert.FromBase64String (stamp);
				wink.Data = File.ReadAllBytes (file);
				
				if ((wink.Data == null) || (wink.Data.Length == 0))
				{
					Log.Error ("Error loading wink");
					return null;
				}
				
				return wink;
			}
			
			Log.Error ("No item node");
			return null;
		}
		
		protected override void OnDataChanged ()
		{
			if (Data.Length == 0)
				return;
			
			_contentDesc = null;
			_thumbnail = string.Empty;
			_animation = string.Empty;
			_width = 0;
			_height = 0;

			string dir = CabExtract.Instance.ExtractToDirectory (CacheFilename);
			
			if (string.IsNullOrEmpty (dir))
			{
				Log.Error ("Unable to extract {0}", CacheFilename);
				Data = new byte[0];
				return;
			}
			
			string contentFile = Path.Combine (dir, "content.xml");
			
			if (!File.Exists (contentFile))
			{
				Log.Error ("No content descriptor {0}", contentFile);
				Data = new byte[0];
				return;
			}
			
			try
			{
				_contentDesc = new XmlDocument ();
				_contentDesc.Load (contentFile);
			}
			catch (XmlException)
			{
				_contentDesc = null;
				Log.Error ("Invalid content descriptor");
				Data = new byte[0];
				return;
			}
			
			if (_contentDesc.DocumentElement.Name != "package")
			{
				Log.Error ("XML document element isn't package");
				Data = new byte[0];
				return;
			}
			
			if (_contentDesc.DocumentElement.GetAttribute ("type") != "wink")
			{
				Log.Error ("Invalid package type '{0}'", _contentDesc.DocumentElement.GetAttribute ("type"));
				Data = new byte[0];
				return;
			}
			
			Friendly = _contentDesc.DocumentElement.GetAttribute ("name", "http://messenger.msn.com/winks/1.0");
			
			foreach (XmlElement elem in _contentDesc.DocumentElement)
			{
				string type = elem.GetAttribute ("type");
				string file = FindCorrectCase (Path.Combine (dir, elem.GetAttribute ("file")));
				
				if (string.IsNullOrEmpty (file) || (!File.Exists (file)))
					continue;
				
				if (type == "animation")
				{
					_animation = file;
					
					foreach (XmlAttribute att in elem.Attributes)
					{
						if (att.LocalName.Equals ("sizex", StringComparison.InvariantCultureIgnoreCase))
							int.TryParse (att.Value, out _width);
						if (att.LocalName.Equals ("sizey", StringComparison.InvariantCultureIgnoreCase))
							int.TryParse (att.Value, out _height);
					}
				}
				else if (type == "thumbnail")
					_thumbnail = file;
			}
			
			base.OnDataChanged ();
		}
		
		static string FindCorrectCase (string filename)
		{
			if (File.Exists (filename))
				return filename;
			
			string dir = System.IO.Path.GetDirectoryName (filename);
			
			if (!Directory.Exists (dir))
				return null;
			
			foreach (string file in Directory.GetFiles (dir))
				if (file.Equals (filename, StringComparison.InvariantCultureIgnoreCase))
					return file;
			
			return null;
		}
	}
}
